--[[
战斗控制器
]]
CardEliminateAll =  require("app.util.CardEliminateAll")
CardUtil =  require("app.util.CardUtil")
local FightController = class("FightController")




--[[
 获取单例
]]
local instance = nil;
function FightController.getInstance()
	if instance == nil then
		instance = FightController.new();
	end
	
	return instance;
end


--[[
战斗控制器 构造函数
@param scene 场景
]]
function FightController:init(scene,levelData)
	--显示场景
	self.scene_  =  scene; 
	
	--模型
	local FightModel = require("app.model.FightModel")
	self.model_ = FightModel.new(self,levelData);
	
	--控制的数据
    self.over_ = false; 
	self.pause_ = false;
	
	self:initView();
end



--[[
初始化
]]
function FightController:initView()
	--初始化地图
	local levelData = self.model_.levelData_;
	local staticData = levelData.static;
	local cardSpriteData = levelData.cardSpriteData;

	
	
	for id,v in pairs(staticData) do
		self.model_:newObject(BaseObject.CLASS_ID["static"], v,id)
	end
	
	
	
	--初始化卡牌
  	local static =  {
        x = 100,
        y = 300,
        focusObject = true,
        defineId  =  "cardSprite"
    }
	for col,v in pairs(cardSpriteData) do
		for row,v1 in pairs(v) do
			local staticId = "static:" ..row .."_"..col ;
			local obj = self.model_:newObject(BaseObject.CLASS_ID["static"], static,staticId)
			local spt = obj:getView();
			obj:setCardSpriteId(v1);
			local x,y = CardUtil.getCardPositionByIndex(row,col);
			obj:setPosition(x,y);
			--添加监听事件
			spt:setTouchEnabled(true)
		    spt:setTouchMode(cc.TOUCH_MODE_ONE_BY_ONE) --单点 TOUCH_MODE_ALL_AT_ONCE多点
		    spt:setTouchSwallowEnabled(true) -- 是否吞噬事件，默认值为 true
		    spt:addNodeEventListener(cc.NODE_TOUCH_EVENT, function(event)
		       self:touchByCardSprite(event,obj);
		       return true;
		    end)
		end
	end
	
	--替换的主卡
	local role = self.model_:getObject("static:0_0");
	role:setPosition(CardUtil.getCardPositionByIndex(0,0));
	role:setCardSpriteId(1);
	local spt = role:getView();
	spt:setTouchEnabled(true)
    spt:setTouchMode(cc.TOUCH_MODE_ONE_BY_ONE) --单点 TOUCH_MODE_ALL_AT_ONCE多点
    spt:setTouchSwallowEnabled(true) -- 是否吞噬事件，默认值为 true
    spt:addNodeEventListener(cc.NODE_TOUCH_EVENT, function(event)
       self:touchByCardSprite(event,role);
       return true;
    end)
	
	
	--当前地图是否可以点击
	self.isClick_ = true;
	
	
	GameCoreManager:addEventListener(EventConstants.Victory, function(event)
		self:overHandle(true);
	end)
	GameCoreManager:addEventListener(EventConstants.Faile, function(event)
		self:overHandle(false);
	end)
	--能量满
	GameCoreManager:addEventListener(EventConstants.CurrentEnergysFull, function(event)
       self.isClick_ = false;
       self:eliminateAll(function()
       		self.model_.fightAccount_.m_energysFull_ = false;
       		self.model_.fightAccount_:addCurrentEnergys(-self.model_.fightAccount_.energyNums_);
       end);
    end)
end








function FightController:createRandomCardSprite(onEndComplete)
	local model = self.model_;
	--3 整理排序 ，将卡片标记不为0的往下拉，为0的往上拉
	local leaveCards = CardEliminateAll.sortCard(model);
	self.scene_:performWithDelay(function()
		--4 创建新的卡片 并往下排
		CardEliminateAll.createRandomCardSprite(model,leaveCards,function()
			self:eliminateAll(onEndComplete);
		end);
	end, 0.4)
end
function FightController:skillOnComplete(allCleanCard,onEndComplete)
	local model = self.model_;
	CardUtil.dispatchSkill(model,allCleanCard,CardUtil.triggerType_eliminate,function()
		self:createRandomCardSprite(onEndComplete);
	end)
end		
			
--全局再次遍历
function FightController:eliminateAll(onEndComplete)
	local model = self.model_;
	
	--1 先获取所有可消除的卡片
	local allCleanCard = CardEliminateAll.getEliminateCard(self.model_);
	if #allCleanCard > 0 then
		
		local onComplete = function(newCleanCard)
			--2.1  插入一个释放技能  所有完毕  在调用FightController:createRandomCardSprite(onEndComplete)创建卡牌
			self:skillOnComplete(allCleanCard,onEndComplete)
		end
		
		--2 将卡片的卡片标记为0
		CardEliminateAll.eliminateCard(self.model_,allCleanCard,onComplete);
		
	else
		self.isClick_ = true;
		GameCoreManager:dispatchEvent({name=EventConstants.EliminateAll,data =nil})
		if onEndComplete then 
			onEndComplete();
		end
	end
end










--事件响应
function FightController:touchByCardSprite(event,targetCard)	
	if self.over_  or self.pause_ then return end
	--过滤掉不能点击的球
	local targetCardId = targetCard:getId();
	if targetCardId == "static:0_0" then return end
	
	
	printf("%s %s [TARGETING]", "button1", event.name)
	local role = self.model_:getObject("static:0_0");
	local roleCardSpriteId = role.cardSpriteId_;
	
	
	
    if event.name == "ended" then
    	if self.isClick_ then
    		self.isClick_ = false;
    		self.model_.fightAccount_:addStepNums();
    		
    		
    		local roleCardSpriteId = role.cardSpriteId_;
			local targetCardSpriteId = targetCard.cardSpriteId_;
			
			local targetXIndex,targetYIndex = targetCard:getXYIndexById();
			local targetX,targetY = CardUtil.getCardPositionByIndex(targetXIndex,targetYIndex)
			role:moveTo(targetX,targetY);
			
			local roleXIndex,roleYIndex = role:getXYIndexById();
			local roleX,roleY = CardUtil.getCardPositionByIndex(roleXIndex,roleYIndex)
			targetCard:moveTo(roleX,roleY,function()
					--更改id
					local roleId = role:getId();
					local targetId = targetCard:getId()
					role:changeId(targetId);
					targetCard:changeId(roleId);
					
					if self.model_.levelType_ == 0 then
						self:eliminateAll();
					else
						self.isClick_ = true;
					end
			end);
			
			
	    	
	    	
	    	
    	end
    	
    elseif event.name == "cancelled" then
       
    end
    
    
    return true
end

















function FightController:play()
	if self.pause_ then 
		self:resumePlay() 
	else
		self:pausePlay() 
	end
end
--暂停 
function FightController:pausePlay()
	if self.pause_ then return end
	
	self.pause_ = true;
	
	local model = self.model_
	local allObject = model:getAllObjects();
	
	for k,obj in pairs(allObject) do 
		--obj:stopMovingNow();
		obj:pausePlay();
	end
end
--播放
function FightController:resumePlay()
	if not self.pause_ then return end
	
	
	self.pause_ = false;
	
	local model = self.model_
	local allObject = model:getAllObjects();
	
	
	for k,obj in pairs(allObject) do 
			--obj:startMovingNow();
			obj:resumePlay();
	end
end
function FightController:overHandle(isWin)
	if self.over_ then return end
	
	self.over_ = true;
	isWin = checkbool(isWin);
	
	
	
	
	local c = SpriteCover.createCoverSprite()
    self.scene_:addChild(c);
    -- local cover = cc.LayerColor:create(cc.c4b(0, 0, 0, 255),display.width, display.height):addTo(self.scene_)
	--cover:setPosition(display.cx,display.cy);
      --self.scene_:addChild(cover);
     
    
	
	cc.ui.UILabel.new({
    text = "game is ove，you win is "..tostring(isWin),
    size = 45,
    color = display.COLOR_RED,
	}):align(display.BOTTOM_LEFT, display.left + 20, display.cy):addTo(self.scene_)
	
	
	 cc.ui.UIPushButton.new({normal = "#set_daanniu.png", pressed = "#set_daanniu.png"})
        :align(display.CENTER, display.cx, display.cy - 150)
        :setButtonLabel("normal", cc.ui.UILabel.new({
            UILabelType = 2,
            text = "restart",
            size = 18
        }))
        :onButtonClicked(function()
        	self.model_:destroy();
        	self.model_ = nil;
            app:back();
        end)
        :addTo(self.scene_)

end












--tick帧跳
function FightController:tick(dt)
	if  self.pause_ or self.over_ then return end;
	
	local model = self.model_
	local allObject = model:getAllObjects();
	model.fightAccount_:tick(dt);
--	if  self.pause_  then return end;
--	
--	
--	if not self.over_ then 
--		--检测碰撞相关
--		for i, object in pairs(allObject) do
--			if object ~= self.plane then 
--				local collision = SearchAlgorithm.checkCollision(object,self.plane)
--				if collision then 
--					self.over_ = true;
--					
--					--播放死忙特效
--					object:setDestroyed(true);
--					self.plane:setDestroyed(true);
--					
--					return;
--				end
--			end
--		end
--	end
--	
--	
--
	local maxZOrder = SceneConstants.MAX_OBJECT_ZORDER;
	for i, object in pairs(allObject) do
		local lx, ly = object.x_, object.y_
        object:tick(dt)
        object.updated__ = lx ~= object.x_ or ly ~= object.y_

		--[[
        -- 只有当对象的位置发生变化时才调整对象的 ZOrder
        if object.sprite_ and object.updated__ then
        	object:updateView();
        	
        	if object.viewZOrdered_ then 
        		local batch = self.scene_:getBatchLayer();
            	batch:reorderChild(object.sprite_, maxZOrder - object.y_ )
            end
        end
        ]]
        
	end
end


return FightController
